const { contextBridge, ipcRenderer } = require('electron');

/**
 * The preload script runs before. It has access to web APIs
 * as well as Electron's renderer process modules and some
 * polyfilled Node.js functions.
 * 
 * https://www.electronjs.org/docs/latest/tutorial/sandbox
 */
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const type of ['chrome', 'node', 'electron']) {
    replaceText(`${type}-version`, process.versions[type])
  }
})


const api = {
  // 获取应用版本
  getAppVersion: async () => {
    return await ipcRenderer.invoke('app:getVersion');
  },
  // 获取系统信息
  getAppInfo: async () => {
    return await ipcRenderer.invoke('api:getInfo');
  },
  // 获取打印机列表
  getPrinters: async () => {
    return await ipcRenderer.invoke('api:getPrinters');
  },
  // 获取本地字体列表
  getLocalFonts: async () => {
    return await ipcRenderer.invoke('api:getLocalFonts');
  },
  // 选择目录
  selectDirectory: async (params = {}) => {
    return await ipcRenderer.invoke('api:selectDirectory', params);
  },
  // 重启
  restart: async () => {
    return await ipcRenderer.invoke('api:restart');
  }
}


contextBridge.exposeInMainWorld('api', api);

/**
 * TTS
 */
const tts = {

  /**
   * 播报 
   * @param {Object} params 播报参数
   * @param {string} params.text 播报的文本
   * @param {number} params.rate 语速
   * @param {string} params.lang 语言
   */
  speak: (params) => ipcRenderer.send('tts:render:speak', params),
}
// 内部页面可以调用
contextBridge.exposeInMainWorld('tts', tts);

// 来自主进程的 IPC 播报指令
ipcRenderer.on('tts:render:speak', (event, params) => {
  console.log('[TTS] 开始播报：', params);
  if (!params.text) {
    console.log('[TTS] 播报失败：', params);
    return;
  }
  // 默认参数
  let options = Object.assign({
    text: '',
    rate: 1.5,
    lang: 'zh-CN'
  }, params);
  const utterance = new SpeechSynthesisUtterance(options.text);
  // 设置语言
  utterance.lang = options.lang;
  // 设置语速 语速范围 0.1 - 10
  utterance.rate = options.rate;

  const voices = speechSynthesis.getVoices();
  const zhVoice = voices.find(v => v.lang.startsWith('zh') && v.localService);
  if (zhVoice) utterance.voice = zhVoice;
  speechSynthesis.cancel();
  speechSynthesis.speak(utterance);
});


const electronStore = {
  // 将所有方法改为同步
  get: (key) => ipcRenderer.sendSync('electronStore:getSync', key),
  set: (key, value) => ipcRenderer.sendSync('electronStore:setSync', key, value),
  delete: (key) => ipcRenderer.sendSync('electronStore:deleteSync', key),
}
contextBridge.exposeInMainWorld('electronStore', electronStore);